<?php
/**     
  *
  * Copyright (c) 2009, Persistent Systems Limited
  *
  * Redistribution and use, with or without modification, are permitted 
  *  provided that the following  conditions are met:
  *   - Redistributions of source code must retain the above copyright notice, 
  *     this list of conditions and the following disclaimer.
  *   - Neither the name of Persistent Systems Limited nor the names of its contributors 
  *     may be used to endorse or promote products derived from this software 
  *     without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
/**
 * File path for authenticationModel.php
 */
require_once 'model/authenticationModel.php';
/**
 * Authenticate_Controller class to authenticate User Login/Logout process
 * @access public
 */
/**
 * Authenticate_Controller class to authenticate User Sign In/ Sign Out process
 *
 * @access public
 */
class Authenticate_Controller
{
	/**
     * @access private
     * @var string 
     */
	private $_authorization = "Required";
	/**
     * @access private
     * @var string 
     */
	private $_maxMessageCount = "10";
	/**
     * @access private
     * @var string 
     */
	private $_expiresAfter = "24";
	/**
     * @access private
     * @var string 
     */
	private $_transportProtection = "None";

	/**
	* HTTP prorocol for curl request
	*
	* @var string $requestProtocol
	* @access private
	*/
	const requestProtocol = 'http';
    /** 
     * Class constructor
	 */
	public function __construct()
	{

	}

	/**
	 * This function display Login Page
	 * @access public
	 */
	public function showLoginPage()
	{
		try{
			if($_POST){
				$authModel = new AuthenticationModel();
				$errors = $authModel->validateUserLogin($_POST);
				if (count($errors) ==  0){
					$this->doLogin($_POST);
				}
			}
			//Show Login Template
			include_once('view/login.php');
			exit;
		} catch (Exception $e){
			throw ($e);
		}
	}

	/**
	 * This function do process of login on given login credentials
	 * @access public
	 * @param array $userLoginInfo Array of username and password
	 * @return void on successful authentication redirect user to home page else display error message
	 */
	public function doLogin($userLoginInfo)
	{
		try{

			$serviceName = trim($userLoginInfo['txtUsername']); // live id is replaced by solution name for now
			$issuerKey = trim($userLoginInfo['txtPassword']); // password will be the issuerKey
			
			//REST call and getting token  
			$authModel = new AuthenticationModel();

			
			$response = $authModel->authAcs($serviceName,$issuerKey);
			 
			if(empty($response['error']))
			{
				$_SESSION['salesPersionID'] = 1;
				$_SESSION['token'] = $response['token'];

				//create message buffer with session id
				if(HTTP_REQUEST_VIA_MSG_BUFFER){
					$policy = new MessageBufferPolicy();
					$policy->authorization = $this->_authorization;
					$policy->maxMessageCount =  $this->_maxMessageCount;
					$policy->expiresAfter = $this->_expiresAfter;
					$policy->transportProtection = $this->_transportProtection;			
					
					//Prepare Scope object by passing with appropriate values needed by service bus to create message buffer
					$scopeForServiceBus = new Scope(CREDENTIAL_TYPE);			

					$scopeForServiceBus->setIssuerName(ISSUER_NAME);
					$scopeForServiceBus->setIssuerSecret(ISSUER_SECRET_KEY);
					$scopeForServiceBus->setServiceNamespaceDomain(SERVICE_NAMESPACE_DOMAIN);

					$proxyForServiceBus = new HttpWebProxy(HTTP_PROXY_HOST, HTTP_PROXY_PORT);
					//create message buffer with session id
					$messageBufferUri = DotNetServicesEnvironment::getMessageBufferUri(self::requestProtocol,$scopeForServiceBus->getServiceNamespaceDomain(), session_id()) ;
					$responseClient = new MessageBufferClient($messageBufferUri, $scopeForServiceBus, $policy, $proxyForServiceBus); 
					$responseClient->createMessageBuffer($policy);
				}
				
				header('location:index.php');
			}
			$errors = $response['error'];
			include_once('view/login.php');
			
 		
		} catch(Exception $e){
			throw ($e);
		}
	}
	/**
	 * Function to do process of log out user from application
	 * @access public
	 * @return void on successful authentication log outs user from web app and redirect to login page 
	 */
	public function doLogout()
	{
		try{

			if(isset($_SESSION['salesPersionID'])){
				session_destroy();
				header('location:index.php');
			}

		} catch(Exception $e){
			throw ($e);
		}

	}
}
$authenticateUser  = new Authenticate_Controller();
?>